laravel can't get the three solutions of session [recommended]

  • 2021-11-01 23:56:53
  • OfStack

Problem: When referencing the third-party class library, you can save session using the global function session (), but you can't get it

1. The route is placed under the web middleware, and the file app/Http/Kernel. php is modified as follows


protected $middlewareGroups = [
  // Middleware web
  'web' => [
   \App\Http\Middleware\EncryptCookies::class,
   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
   // See here! StartSession ! ! ! ! It will not start until the route is put in this middleware Session ! ! 
   \Illuminate\Session\Middleware\StartSession::class,
   \Illuminate\View\Middleware\ShareErrorsFromSession::class,
   \App\Http\Middleware\VerifyCsrfToken::class,
  ],
 
  'api' => [
   'throttle:60,1',
  ],
 ];

2. Modify the route writing as follows


// Two kinds of routing middleware writing everyone likes! 
Route::get('/', function () {
 // The route is put here 
})->middleware('web');
 
Route::group(['middleware' => ['web']], function () {
 // The route is put here 
});
//routes.php

3. Laravel does not use the native session of php, so after controller, something should be done to write session to a file, instead of writing every put operation, which will cause IO operation to be too frequent and affect performance.

View the code associated with the call. After laravel is compiled, in bootstrap/compiled. php


class Middleware implements HttpKernelInterface
{
 ...
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
  $this->checkRequestForArraySessions($request);
  if ($this->sessionConfigured()) {
   $session = $this->startSession($request); //  Start session
   $request->setSession($session);
  }
  $response = $this->app->handle($request, $type, $catch); //  Call controller Adj. method
  if ($this->sessionConfigured()) {
   $this->closeSession($session);   // Shut down session
   $this->addCookieToResponse($response, $session);
  }
  return $response;
 }
 ...
 
 protected function closeSession(SessionInterface $session)
 {
  $session->save(); //  Save session
  $this->collectGarbage($session);
 }
}

As you can see, after calling controller, session is called- > save () to actively save session. In this way, session can be saved on the ground. If exit is written in controller or view; session will not be saved unless you actively write Session:: save () to save it manually. Or put die (); exit (); Change to return!


Related articles: